﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Handrise.Mobile.BasicModal.Serialization;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace Handrise.CDCable.Mobile.Business
{
    /// <summary>
    /// 数据同步类，所有数据交互通过该类进行
    /// </summary>
    public class Synchronize
    {
        //private Control mainTreahComponent;
        private Form mainTreahComponent;

        private CDCalbeWebService.Service webService = new CDCalbeWebService.Service();

        private CallWebServiceCompleteHandler invokeCallWebserviceMessage;

        private bool isAllSynchroize = false; //是否整体同步
        private bool isGISDataSynchronize = false; //是否进行GIS数据同步
        private int allSynchroizeDeviceCount = 0;//所有需要同步的设备个数
        private int synchronizePercent = 0;  //同步进度
        private bool synchronizeHasError = false;

        /// <summary>
        /// 同步过程事件
        /// </summary>
        public event SynchronizeProcessHandler OnSynchronizeProcess;

        /// <summary>
        /// 地图数据同步过程事件
        /// </summary>
        public event SynchronizeProcessHandler OnGISDataSynchronizeProcess;

        /// <summary>
        /// 下载巡视计划完成事件
        /// </summary>
        public event CallWebServiceCompleteHandler OnDownloadPlanComplete;

        /// <summary>
        /// 下载指挥信息完成事件
        /// </summary>
        public event CallWebServiceCompleteHandler OnDownloadCommunicationComplete;

        /// <summary>
        /// 上传缺陷完成事件
        /// </summary>
        public event CallWebServiceCompleteHandler OnUploadFlawComplete;

        /// <summary>
        /// 上传计划状态完成事件
        /// </summary>
        public event CallWebServiceCompleteHandler OnUploadPlanStateComplete;

        /// <summary>
        /// 上传GPS轨迹完成事件
        /// </summary>
        public event CallWebServiceCompleteHandler OnUploadGPSTraceComplete;

        /// <summary>
        /// 上传指挥信息完成事件
        /// </summary>
        public event CallWebServiceCompleteHandler OnUploadCommunicationComplete;

        /// <summary>
        /// 上传测温信息完成事件
        /// </summary>
        public event CallWebServiceCompleteHandler OnUploadTempratureComplete;

        /// <summary>
        /// 登录完成事件
        /// </summary>
        public event CallWebServiceCompleteHandler OnLoginComplete;

        public Synchronize()
        {
            //mainTreahComponent = new Control();
            mainTreahComponent = AppLogic.loginForm;
            invokeCallWebserviceMessage = CallWebserviceMessage;
            SetServerUr();
        }

        public string GetUrl()
        {
            return webService.Url;
        }

        private void SetServerUr()
        {
            try
            {
                if (AppLogic.netService.CurrentNetType == NetType.USB)
                {
                    webService.Url = AppLogic.config.GetParameter("Configuration/WebService", "Url");
                }
                else
                {
                    webService.Url = AppLogic.config.GetParameter("Configuration/APN", "Url");
                }
            }
            catch (Exception e)
            {
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        public void Login(string userName, string password)
        {
            try
            {
                webService.BeginLogin(userName, password, LoginComplete, password);
            }
            catch (Exception e)
            {
                CallWebserviceMessage("LoginComplete", false, null);
            }
        }

        /// <summary>
        /// 调用登录完成
        /// </summary>
        /// <param name="ar"></param>
        private void LoginComplete(IAsyncResult ar)
        {
            string password = (string)ar.AsyncState;
            try
            {
                byte[] userBuffer ;
                bool isSuccess = webService.EndLogin(ar, out userBuffer);
                if (!isSuccess)
                {
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "LoginComplete", false, null);
                    return;
                }

                CompactFormatterPlus cfp = new CompactFormatterPlus();
                User user = (User)cfp.Deserialize(userBuffer);
                user.Password = password;

                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "LoginComplete", true, user);

            }
            catch (Exception e)
            {
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "LoginComplete", false, null);
            }
        }

        public string StartSynchrozieGISData()
        {
            //设置WebService地址
            SetServerUr();

            if (AppLogic.netService.CurrentNetType != NetType.USB)
                return "必须使用USB连接才能进行数据同步";

            //关闭GPS轨迹采集，保证在同步的时候没有其他程序访问数据库
            AppLogic.gpsTraceService.Close();

            isGISDataSynchronize = true;
            synchronizePercent = 0;

            ShowInfoToUI("开始同步地图数据...", synchronizePercent);

            //开始获取地图数据文件大小
            webService.BeginGetGISDataLen(GetGISDataLenComplete, null);

            return "";
        }

        /// <summary>
        /// 下载地图数据文件大小完成，开始下载地图数据文件
        /// </summary>
        /// <param name="ar"></param>
        private void GetGISDataLenComplete(IAsyncResult ar)
        {
            try
            {
                long gisFileLen = webService.EndGetGISDataLen(ar) ;

                if (gisFileLen == -1)
                {
                    //获取地图数据文件大小失败
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeGISDataProcess", false, 100);
                    return;
                }

                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeGISDataProcess", true, 10);

                //通过文件大小，获取需要下载的次数
                int downloadCount = (int)(gisFileLen - 1) / (1024 * 100) + 1;
                byte[] buffer;

                //创建临时文件
                string zipFileName = AppLogic.GetLocalPath() + "\\Update\\MapCache.gd";
                FileStream fs = new FileStream(zipFileName, FileMode.Create);

                try
                {
                    try
                    {
                        for (int i = 0; i < downloadCount; i++)
                        {
                            if(webService.SynchronizeGISData(i, out buffer))
                            {
                                fs.Seek(0, SeekOrigin.End);
                                fs.Write(buffer, 0, buffer.Length);

                                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeGISDataProcess", true, i * 80 / downloadCount + 10);
                            }
                            else
                            {
                                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeGISDataProcess", false, 100);
                                return;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeGISDataProcess", false, 100);
                        return;
                    }
                }
                finally
                {
                    fs.Close();
                }

                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeGISDataProcess", false, 90);
                //下载完成,开始更新地图文件
                using (FileStream stream = new FileStream(zipFileName, FileMode.Open))
                {
                    ZipInputStream zipstream = new ZipInputStream(stream);
                    ZipEntry entry = zipstream.GetNextEntry();

                    //创建备份目录
                    string bakDirctory = AppLogic.GetLocalPath() + "\\Update\\MapBak" + DateTime.Now.ToString("yyyyMMdd");
                    Directory.CreateDirectory(bakDirctory);

                    //删除旧地图数据文件
                    try
                    {
                        string[] allGISFile = Directory.GetFiles(AppLogic.GetLocalPath() + "\\MapCache");
                        foreach (string gisFile in allGISFile)
                        {
                            File.Delete(gisFile);
                        }
                    }
                    catch (Exception e)
                    {
                    }


                    while (entry != null)
                    {
                        try
                        {
                            if (entry.IsFile)
                            {
                                //是文件
                                int readlength;
                                byte[] buff = new byte[1024 * 100];
                                string targetFile = AppLogic.GetLocalPath() + "\\MapCache\\" + entry.Name.Replace('/', '\\');

                                //清除只读属性
                                if (File.Exists(targetFile))
                                {

                                    FileInfo fi = new FileInfo(targetFile);

                                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                                    {

                                        fi.Attributes = FileAttributes.Normal;
                                    }
                                }

                                using (FileStream outputStream = new FileStream(targetFile, FileMode.Create))
                                {
                                    while (true)
                                    {
                                        readlength = zipstream.Read(buff, 0, buff.Length);

                                        if (readlength <= 0)
                                        {
                                            break;
                                        }

                                        outputStream.Seek(0, SeekOrigin.End);
                                        outputStream.Write(buff, 0, readlength);

                                    }
                                }
                            }

                            if (entry.IsDirectory)
                            {
                                //是目录
                                string targetDirectory = AppLogic.GetLocalPath() + "\\MapCache\\" + entry.Name.Replace('/', '\\');
                                if (!Directory.Exists(targetDirectory))
                                {
                                    Directory.CreateDirectory(targetDirectory);
                                }
                            }
                        }
                        catch (Exception ex)
                        {

                        }
                        entry = zipstream.GetNextEntry();
                    }
                }

                //更新完成
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeGISDataProcess", true,100);
            }
            catch (Exception e)
            {
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeGISDataProcess", false, 100);
                return;
            }

        }

        /// <summary>
        /// 开始同步
        /// </summary>
        public string StartSynchronize()
        {
            //设置WebService地址
            SetServerUr();

            if (AppLogic.netService.CurrentNetType != NetType.USB)
                return "必须使用USB连接才能进行数据同步";

            //关闭GPS轨迹采集，保证在同步的时候没有其他程序访问数据库
            AppLogic.gpsTraceService.Close();

            isAllSynchroize = true;
            synchronizePercent = 0;
            synchronizeHasError = false;

            ShowInfoToUI("开始同步数据", synchronizePercent);
            //上传，上传GPS轨迹信息、指挥信息、测温信息、任务状态、巡视详情、缺陷信息

            SynchronizeNext();

            return "";
        }

        /// <summary>
        /// 下载巡视计划
        /// </summary>
        /// <param name="userName"></param>
        public void DownloadPlan(string userName)
        {
            webService.BeginDownloadPlan(AppLogic.LoginUser.UserName, DownloadPlanComplete, null);
        }

        /// <summary>
        /// 下载巡视计划完成
        /// </summary>
        /// <param name="ar"></param>
        private void DownloadPlanComplete(IAsyncResult ar)
        {
            try
            {
                byte[] plansBuffer ;
                byte[] planDevicesBuffer;
                byte[] flawsBuffer ;
                byte[] communicationsBuffer ;
                if (!webService.EndDownloadPlan(ar, out plansBuffer, out planDevicesBuffer, out flawsBuffer, out communicationsBuffer))
                {
                    //巡视计划下载失败
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "DownloadPlanComplete", false, null);
                    return;
                }
                
                //处理数据
                CompactFormatterPlus cfp = new CompactFormatterPlus();

                //巡视设备
                List<Object> planDevices = (List<Object>)cfp.Deserialize(planDevicesBuffer);
                PlanDeviceService planDeviceService = new PlanDeviceService();
                planDeviceService.DealNewReceivedPlanDevice(planDevices);

                //巡视计划
                List<Object> plans = (List<Object>)cfp.Deserialize(plansBuffer);
                PlanService planService = new PlanService();
                planService.DealNewReceivedPlan(plans);

                //缺陷
                List<Object> flaws = (List<Object>)cfp.Deserialize(flawsBuffer);
                FlawService flawService = new FlawService();
                flawService.DealNewReceivedFlaw(flaws);

                //指挥信息
                List<Object> commnunications = (List<Object>)cfp.Deserialize(communicationsBuffer);
                CommunicationService communicationService = new CommunicationService();
                communicationService.DealNewReceivedCommunication(commnunications);

                //调用巡视计划下载完成接口
                string planIDs = "" ;
                foreach (Plan plan in plans)
                {
                    planIDs += "," + plan.PlanID;
                }
                if (planIDs != "")
                    planIDs = planIDs.Remove(0, 1);
                string communicationIDs = "";
                foreach (Communication communication in commnunications)
                {
                    communicationIDs += "," + communication.CommunicationID;
                }
                if (communicationIDs != "")
                    communicationIDs = communicationIDs.Remove(0, 1);
                if(communicationIDs != "" || planIDs !="")
                    webService.ComfireDownloadPlan(AppLogic.LoginUser.UserName, planIDs, communicationIDs);

                //巡视计划同步完毕
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "DownloadPlanComplete", true,null);
            }
            catch (Exception e)
            {
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "DownloadPlanComplete", false, null);
                return;
            }

        }

        /// <summary>
        /// 下载指挥信息
        /// </summary>
        /// <param name="userName"></param>
        public void DownloadCommunication(string userName)
        {
            webService.BeginDownloadCommunication(userName, DownloadCommunicationComplete, null);
        }

        /// <summary>
        /// 下载指挥信息完成
        /// </summary>
        /// <param name="ar"></param>
        private void DownloadCommunicationComplete(IAsyncResult ar)
        {
            try
            {
                byte[] communicationsBuffer;
                if (!webService.EndDownloadCommunication(ar, out communicationsBuffer))
                {
                    //下载指挥信息失败
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "DownloadCommunicationComplete", false, null);
                    return;
                }

                //处理数据
                CompactFormatterPlus cfp = new CompactFormatterPlus();

                //指挥信息
                List<Object> commnunications = (List<Object>)cfp.Deserialize(communicationsBuffer);
                CommunicationService communicationService = new CommunicationService();
                communicationService.DealNewReceivedCommunication(commnunications);

                //调用指挥信息下载确认接口
                string communicationIDs = "";
                foreach (Communication communication in commnunications)
                {
                    communicationIDs += "," + communication.CommunicationID;
                }
                if (communicationIDs != "")
                    communicationIDs = communicationIDs.Remove(0, 1);
                if (communicationIDs != "")
                    webService.ComfireDownloadPlan(AppLogic.LoginUser.UserName, "", communicationIDs);

                //下载指挥信息完毕
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "DownloadCommunicationComplete", true, commnunications);
            }
            catch (Exception e)
            {
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "DownloadCommunicationComplete", false, null);
                return;
            }
        }

        /// <summary>
        /// 下载标准数据和设备数据
        /// </summary>
        /// <param name="userName">用户</param>
        public void DownloadStandardDataAndDevice(string userName)
        {
            //获取最后更新设备时间
            string deviceUpdateDateTime = "";
            SysConfigService sysConfigService = new SysConfigService();
            SysConfig sysConfig = sysConfigService.GetSysConfig("DeviceUpdateDateTime");
            if (sysConfig == null)
            {
                sysConfig = new SysConfig();
                sysConfig.SysConfigID = Guid.NewGuid().ToString();
                sysConfig.KeyName = "DeviceUpdateDateTime";
                sysConfig.KeyValue = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                deviceUpdateDateTime = sysConfig.KeyValue;
                sysConfig.KeyValue = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            webService.BeginDownloadStandardDataAndDevice(userName, deviceUpdateDateTime, DownloadStandardDataAndDeviceComplete, sysConfig);
        }

        /// <summary>
        /// 下载标准数据和设备数据到服务器完成
        /// </summary>
        /// <param name="ar"></param>
        private void DownloadStandardDataAndDeviceComplete(IAsyncResult ar)
        {
            try
            {
                string re = webService.EndDownloadStandardDataAndDevice(ar);
                SysConfig sysConfig = (SysConfig)ar.AsyncState;
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "DownloadStandardDataAndDeviceComplete", true, null);

                //获取需要同步的设备,开始同步
                if (re == "")
                {
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeDeviceComplete", true, null);
                    return;
                }
                else if(re == "Error")
                {
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeDeviceComplete", false, null);
                    return;
                }

                string[] deviceInfoList = re.Split(';');
                int index = 1;
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeDeviceBegin", true, deviceInfoList.Length);
                foreach (string deviceInfo in deviceInfoList)
                {
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeSingleDeviceBegin", true, index);
                    try
                    {
                        string[] infos = deviceInfo.Split(',');
                        if (infos.Length == 4)
                        {
                            byte[] devicesBuffer;
                            byte[] deviceDetailsBuffer;
                            byte[] standardDataBuffer;
                            byte[] deviceGPSBuffer;
                            //同步设备和标准数据
                            int dataType = int.Parse(infos[3]);
                            //获取数据个数
                            int entiyCount = int.Parse(infos[2]);
                            int requestCount = (entiyCount - 1) / 100 + 1;

                            //一次同步100个数据，否则内存会不够用
                            for (int i = 0; i < requestCount; i++)
                            {
                                int beginIndex = i * 100; //请求的开始点
                                if (dataType == 0)
                                {
                                    //设备数据
                                    if (webService.SynchronizeDevice(infos[1], beginIndex, out devicesBuffer, out deviceDetailsBuffer))
                                    {
                                        //把获取到的二进制流进行反序列化
                                        CompactFormatterPlus cfp = new CompactFormatterPlus();
                                        List<Device> devices = (List<Device>)cfp.Deserialize(devicesBuffer);
                                        List<Object> deviceDetails = (List<Object>)cfp.Deserialize(deviceDetailsBuffer);

                                        //更新设备
                                        DeviceService devcieService = new DeviceService();
                                        devcieService.UpdateDevices(devices, deviceDetails, infos[0]);
                                    }
                                }
                                else if(dataType ==1)
                                {
                                    //标准数据
                                    if (webService.SynchronizeStandardData(infos[1], beginIndex, out standardDataBuffer))
                                    {
                                        //把获取到的二进制流进行反序列化
                                        CompactFormatterPlus cfp = new CompactFormatterPlus();
                                        List<Object> standardDatas = (List<Object>)cfp.Deserialize(standardDataBuffer);

                                        //更新标准数据
                                        StandardDataService standardDataService = new StandardDataService();
                                        standardDataService.UpdateStandardData(standardDatas, infos[0]);
                                    }

                                }
                                else if (dataType == 2)
                                {
                                    //设备GPS数据
                                    if (webService.SynchronizeDeviceGPSData(infos[1], beginIndex, out deviceGPSBuffer))
                                    {
                                        //把获取到的二进制流进行反序列化
                                        CompactFormatterPlus cfp = new CompactFormatterPlus();
                                        List<DeviceGPS> deviceGPSList = (List<DeviceGPS>)cfp.Deserialize(deviceGPSBuffer);

                                        //更新设备GPS数据
                                        DeviceGPSService seviceGPSService = new DeviceGPSService();
                                        seviceGPSService.UpdateDeviceGPSList(deviceGPSList);
                                    }
                                }
                                GC.Collect();
                            }
                            mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeSingleDeviceComplete", true, index);
                        }
                    }
                    catch (Exception e)
                    {

                    }

                    index++;
                }

                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeDeviceComplete", true, null);


                //更新数据同步时间参数
                SysConfigService sysConfigService = new SysConfigService();
                sysConfigService.UpdateSysConfig(sysConfig);
            }
            catch(Exception e) 
            {
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "SynchronizeDeviceComplete", false, null);
               // mainTreahComponent.Invoke(invokeShowInfo, "同步设备失败...", 100);
            }

        }

        private void ShowInfoToUI(string info,int percent)
        {
            if (percent >= 100)
            {
                //同步结束
                isAllSynchroize = false;

                //同步完成，清理不再需要的数据
                //清除不再关联的文件
                ClearTempFile();

                //开启GPS轨迹采集
                AppLogic.gpsTraceService.Start();

            }

            if (OnSynchronizeProcess != null)
                OnSynchronizeProcess(info, percent);
        }

        /// <summary>
        /// 清除临时的照片文件和录音文件
        /// </summary>
        private void ClearTempFile()
        {
            //获取所有关联的文件信息
            LinkFileService linkFileService = new LinkFileService() ;
            List<LinkFile> linkFiles = linkFileService.GetAllLinkFile();

            //获取所有照片目录下的文件
            string[] fileNames = Directory.GetFiles(AppLogic.GetLocalPath() + "\\Photo");
            //删除多余的文件
            foreach (string fileName in fileNames)
            {
                if (linkFiles.Where(t => t.FullFileName == fileName).Count() == 0)
                {
                    try
                    {
                        File.Delete(fileName);
                    }
                    catch
                    {
                    }

                }
            }

            //获取所有录音目录下的文件
            fileNames = Directory.GetFiles(AppLogic.GetLocalPath() + "\\Audio");
            //删除多余的文件
            foreach (string fileName in fileNames)
            {
                if (linkFiles.Where(t => t.FullFileName == fileName).Count() == 0)
                {
                    try
                    {
                        File.Delete(fileName);
                    }
                    catch
                    {
                    }

                }
            }

        }

        /// <summary>
        /// 调用WebService通知
        /// </summary>
        /// <param name="info">信息</param>
        /// <param name="isSuccess">调用是否成功</param>
        /// <param name="userDataa">用户数据</param>
        private void CallWebserviceMessage(string info, bool isSuccess, object userData)
        {
            switch (info)
            {
                case "DownloadStandardDataAndDeviceComplete": //下载标准数据和设备到服务器完成
                    DoDownloadStandardDataAndDeviceComplete(isSuccess, userData);
                    break;
                case "SynchronizeDeviceBegin":  //开始同步所有设备
                    DoSynchronizeDeviceBegin(isSuccess, userData);
                    break;
                case "SynchronizeSingleDeviceComplete":  //同步单个设备完成
                    DoSynchronizeSingleDeviceComplete(isSuccess, userData);
                    break;
                case "SynchronizeDeviceComplete":  //同步所有设备完成
                    DoSynchronizeDeviceComplete(isSuccess, userData);
                    break;
                case "DownloadPlanComplete":      //下载计划完成
                    DoDownloadPlanComplete(isSuccess, userData);
                    break;
                case "DownloadCommunicationComplete":      //下载指挥信息完成
                    DoDownloadCommunicationComplete(isSuccess, userData);
                    break;
                case "UploadFlawComplete":  //缺陷上传完成
                    DoUploadFlawComplete(isSuccess, userData);
                    break;
                case "UploadPlanStateComplete":  //计划状态上传完成
                    DoUploadPlanStateComplete(isSuccess, userData);
                    break;
                case "UploadGPSTraceComplete":  //GPS轨迹上传完成
                    DoUploadGPSTraceComplete(isSuccess, userData);
                    break;
                case "UploadCommunicationComplete":  //指挥信息上传完成
                    DoUploadCommunicationComplete(isSuccess, userData);
                    break;
                case "UploadTempratureComplete":  //测温上传完成
                    DoUploadTempratureComplete(isSuccess, userData);
                    break;
                case "UploadPatrolInfoComplete":  //巡视信息上传完成
                    DoUploadPatrolInfoComplete(isSuccess, userData);
                    break;
                case "LoginComplete":  //登录完成
                    DoLoginComplete(isSuccess, userData);
                    break;
                case "SynchronizeGISDataProcess":  //同步地图数据过程
                    DoSynchronizeGISDataProcess(isSuccess, userData);
                    break;
            }
        }

        /// <summary>
        /// 下载标准数据和设备到服务器完成后的处理
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="userData"></param>
        private void DoDownloadStandardDataAndDeviceComplete(bool isSuccess, object userData)
        {
            if (!isSuccess)
                synchronizeHasError = true ;

            synchronizePercent += 5;
            ShowInfoToUI("下载标准数据和设备到服务器完成", synchronizePercent);

        }

        /// <summary>
        /// 开始同步所有设备后的处理
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="userData"></param>
        private void DoSynchronizeDeviceBegin(bool isSuccess, object userData)
        {
            if (!isSuccess)
                synchronizeHasError = true; 
            
            allSynchroizeDeviceCount = (int)userData;
            ShowInfoToUI("同步设备和标准数据...", synchronizePercent);
        }

        /// <summary>
        /// 同步单个设备完成后的处理
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="userData"></param>
        private void DoSynchronizeSingleDeviceComplete(bool isSuccess, object userData)
        {
            if (isSuccess)
            {
                int index = (int)userData;
                ShowInfoToUI("同步设备和标准数据...", synchronizePercent + 30 * index / allSynchroizeDeviceCount);
            }
            else
            {
                synchronizeHasError = true;
            }
        }

        /// <summary>
        /// 同步所有设备完成后的处理
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="userData"></param>
        private void DoSynchronizeDeviceComplete(bool isSuccess, object userData)
        {
            if (isSuccess)
            {
                ShowInfoToUI("同步巡视计划...", 95);
                //开始下载巡视计划
                DownloadPlan(AppLogic.LoginUser.UserName);
            }
            else
            {
                synchronizeHasError = true;

                ShowInfoToUI("同步结束,同步设备和标准数据出错", 100);
                //下载地图数据失败，不再下载计划
                return;
            }

        }


        /// <summary>
        /// 下载计划完成后的处理
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="userData"></param>
        private void DoDownloadPlanComplete(bool isSuccess, object userData)
        {
            //是否是有线同步下载整体数据
            if (isAllSynchroize)
            {

                if (!isSuccess)
                {
                    synchronizeHasError = true;
                }

                string info = synchronizeHasError ? "同步完成，同步过程中有部分过程出错" : "同步完成";
                ShowInfoToUI(info, 100);
            }
            else
            {
                //单个调用下载计划后，抛出完成事件
                if (OnDownloadPlanComplete != null)
                {
                    OnDownloadPlanComplete("下载巡视计划完成", isSuccess, userData);
                }
            }
        }

        /// <summary>
        /// 缺陷上传完成后的处理
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="userData"></param>
        private void DoUploadFlawComplete(bool isSuccess, object userData)
        {
            //是否是有线同步下载整体数据
            if (isAllSynchroize)
            {
                synchronizePercent += 10;
                
                if (isSuccess)
                {
                    ShowInfoToUI("上传缺陷信息完成", synchronizePercent);
                }
                else
                {
                    synchronizeHasError = true;
                    ShowInfoToUI("上传缺陷信息失败", synchronizePercent);
                }

                SynchronizeNext();
            }
            else
            {
                //单个调用上传缺陷后，抛出完成事件
                if (OnUploadFlawComplete != null)
                {
                    OnUploadFlawComplete("上传缺陷信息完成",isSuccess,userData);
                }
            }

            //改变缺陷的上传状态
            List<Flaw> flaws = (List<Flaw>)userData;
            if (flaws.Count > 0)
            {
                FlawService flawService = new FlawService();
                string newState = isSuccess ? "已上报" : "未上报";
                flawService.UpdateReportState(flaws, newState);

                if (isSuccess)
                {
                    //删除已上报的处理过的“待消缺缺陷”
                    flawService.DeleteReportDealFlaw();
                }
            }

        }

        /// <summary>
        /// 上传计划状态完成后的处理
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="userData"></param>
        private void DoUploadPlanStateComplete(bool isSuccess, object userData)
        {
            //是否是有线同步下载整体数据
            if (isAllSynchroize)
            {
                synchronizePercent += 10;
                
                if (isSuccess)
                {
                    ShowInfoToUI("上传计划状态信息完成", synchronizePercent);

                    //如果计划已完成，删除计划
                    PlanService planService = new PlanService();
                    List<Plan> plans = (List<Plan>)userData ;
                    foreach (Plan  plan in plans)
                    {
                        if(plan.State == "已完成")
                        planService.DeletePlan(plan.PlanID) ;

                    }
                }
                else
                {
                    synchronizeHasError = true;
                    ShowInfoToUI("上传计划状态信息失败", synchronizePercent);
                }

                SynchronizeNext();
            }
            else
            {
                //单个调用上传缺陷后，抛出完成事件
                if (OnUploadPlanStateComplete != null)
                {
                    OnUploadPlanStateComplete("上传计划状态信息完成", isSuccess, userData);
                }
            }

        }

        /// <summary>
        /// 上报轨迹信息完成后的处理
        /// </summary>
        /// <param name="isSuccess">是否成功</param>
        /// <param name="userData">用户参数</param>
        private void DoUploadGPSTraceComplete(bool isSuccess, object userData)
        {
            //是否是有线同步下载整体数据
            if (isAllSynchroize)
            {
                synchronizePercent += 10;
                if (isSuccess)
                {
                    ShowInfoToUI("上传GPS轨迹信息完成", synchronizePercent);

                    //删除当前用户的轨迹信息
                    AppLogic.gpsTraceService.DeleteGPSTraceByUser(AppLogic.LoginUser.UserName);
                }
                else
                {
                    synchronizeHasError = true;
                    ShowInfoToUI("上传GPS轨迹信息失败", synchronizePercent);
                }

                //开始上传下一个
                SynchronizeNext();

            }
            else
            {
                //更新上报状态
                string newState = isSuccess ?"已上报":"未上报";
                GPSUploadDateTime gpsUploadDateTime = (GPSUploadDateTime)userData ;
                if (gpsUploadDateTime.BeginDateTime.HasValue && gpsUploadDateTime.EndDateTime.HasValue)
                {
                    //更新轨迹状态
                    AppLogic.gpsTraceService.UpdateGPSTraceReportState(gpsUploadDateTime.BeginDateTime.Value, gpsUploadDateTime.EndDateTime.Value, newState);

                }

                //单个调用上传轨迹后，抛出完成事件
                if (OnUploadGPSTraceComplete != null)
                {
                    OnUploadGPSTraceComplete("上传GPS轨迹信息完成", isSuccess, userData);
                }
            }

        }

        /// <summary>
        /// 上传指挥信息完成后的处理
        /// </summary>
        /// <param name="isSuccess">调用是否成功</param>
        /// <param name="userData">调用前传入的用户数据</param>
        private void DoUploadCommunicationComplete(bool isSuccess, object userData)
        {
            //是否是有线同步下载整体数据
            if (isAllSynchroize)
            {
                synchronizePercent += 10;
                if (isSuccess)
                {
                    ShowInfoToUI("上传指挥信息完成", synchronizePercent);
                }
                else
                {
                    synchronizeHasError = true;
                    ShowInfoToUI("上传指挥信息失败", synchronizePercent);
                }

                SynchronizeNext();

            }
            else
            {

                //单个调用上传指挥信息后，抛出完成事件
                if (OnUploadCommunicationComplete != null)
                {
                    OnUploadCommunicationComplete("上传指挥信息完成", isSuccess, userData);
                }
            }

            //更新上传状态
            List<Communication> communications = (List<Communication>)userData;
            if (communications.Count > 0)
            {
                string newState = isSuccess ? "已上报" : "未上报";

                CommunicationService communicationService = new CommunicationService();
                communicationService.UpdateReportState(communications, newState);

            }
        }

        /// <summary>
        /// 上传测温信息完成后的处理
        /// </summary>
        /// <param name="isSuccess">调用是否成功</param>
        /// <param name="userData">调用前传入的用户数据</param>
        private void DoUploadTempratureComplete(bool isSuccess, object userData)
        {
            //是否是有线同步下载整体数据
            if (isAllSynchroize)
            {
                synchronizePercent += 10;
                if (isSuccess)
                {
                    ShowInfoToUI("上传测温信息完成", synchronizePercent);
                }
                else
                {
                    synchronizeHasError = true;
                    ShowInfoToUI("上传测温信息失败", synchronizePercent);
                }

                SynchronizeNext();

            }
            else
            {
                //单个调用测温信息后，抛出完成事件
                if (OnUploadTempratureComplete != null)
                {
                    OnUploadTempratureComplete("上传测温信息完成", isSuccess, userData);
                }
            }

            //更新上传状态或删除已上报的测温信息
            List<Temprature> tempratures = (List<Temprature>)userData;
            if (tempratures.Count > 0)
            {
                TempratureService tempratureService = new TempratureService();
                if (isSuccess)
                {
                    //上报成功，删除上报的测温信息
                    tempratureService.DeleteTemperatures(tempratures);
                }
                else
                {
                    tempratureService.UpdateReportState(tempratures, "未上报");
                }

            }
        }

        /// <summary>
        /// 上传巡视信息完成后的处理
        /// </summary>
        /// <param name="isSuccess">调用是否成功</param>
        /// <param name="userData">调用前传入的用户数据（巡视信息）</param>
        private void DoUploadPatrolInfoComplete(bool isSuccess, object userData)
        {
            //是否是有线同步下载整体数据
            if (isAllSynchroize)
            {
                synchronizePercent += 10;
                
                if (isSuccess)
                {
                    PatrolInfoService patrolInfoService = new PatrolInfoService();
                    patrolInfoService.UpdateReportState("已上报");
                    ShowInfoToUI("上传巡视信息完成", synchronizePercent);
                }
                else
                {
                    synchronizeHasError = true;
                    ShowInfoToUI("上传巡视信息失败", synchronizePercent);
                }

                SynchronizeNext();
            }
        }

        /// <summary>
        /// 登录完成后的处理
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="userData"></param>
        private void DoLoginComplete(bool isSuccess, object userData)
        {
            if (OnLoginComplete != null)
            {
                OnLoginComplete("登录完成", isSuccess, userData);
            }
        }

        /// <summary>
        /// 下载指挥信息后的处理
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="userData"></param>
        private void DoDownloadCommunicationComplete(bool isSuccess, object userData)
        {
            if (OnDownloadCommunicationComplete != null)
            {
                OnDownloadCommunicationComplete("指挥信息下载完成", isSuccess, userData);
            }
        }

        /// <summary>
        /// 处理地图数据同步过程
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="userData"></param>
        private void DoSynchronizeGISDataProcess(bool isSuccess, object userData)
        {
            int percent = (int)userData;
            string info = "" ;
            if (percent <= 10)
                info = "获取地图数据大小";
            else if(percent < 90)
                info = "下载地图数据文件";
            else if (percent < 100)
                info = "更新地图数据文件";
            else if (percent == 100)
            {
                info = isSuccess? "地图数据同步完成" : "地图数据同步失败";
            }

            if (OnGISDataSynchronizeProcess != null)
                OnGISDataSynchronizeProcess(info, percent);
        }
      
 
        /// <summary>
        /// 上传缺陷
        /// </summary>
        /// <param name="flaws"></param>
        public void UploadFlaws(List<Flaw> flaws)
        {
            try
            {
                if (flaws.Count == 0)
                {
                    CallWebserviceMessage("UploadFlawComplete", true, flaws);
                    return;
                }

                //更改缺陷的上传状态为“正在上报”
                FlawService flawService = new FlawService();
                flawService.UpdateReportState(flaws, "正在上报");


                CompactFormatterPlus cfp = new CompactFormatterPlus();
                byte[] flawsBuffer = cfp.Serialize(flaws);
                webService.BeginUploadFlaw(AppLogic.LoginUser.UserName, flawsBuffer, UploadFlawComplete, flaws);

            }
            catch (Exception e)
            {
                CallWebserviceMessage("UploadFlawComplete", false, flaws);
            }
        }

        /// <summary>
        /// 上传缺陷完成
        /// </summary>
        /// <param name="ar"></param>
        private void UploadFlawComplete(IAsyncResult ar)
        {
            List<Flaw> flaws = (List<Flaw>)ar.AsyncState;
            try
            {
                bool isSuccess = webService.EndUploadFlaw(ar);
                if (!isSuccess)
                {
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadFlawComplete", false, flaws);
                    return;
                }
                
                //缺陷信息上传完成，开始上传缺陷相关文件
                string linkIDs = "";
                foreach (Flaw flaw in flaws)
                {
                    linkIDs += ",'" + flaw.FlawID + "'";
                }
                if (linkIDs != "")
                    linkIDs = linkIDs.Remove(0, 1);
                LinkFileService linkFileService = new LinkFileService();
                List<LinkFile> linkFiles = linkFileService.GetNeedReportLinkFileByLinkID(linkIDs);
                string fileIDs = "";
                foreach (LinkFile linkFile in linkFiles)
                {
                    //更新文件上传状态
                    linkFile.ReportState = "正在上报" ;
                    linkFileService.UpdateLinkFile(linkFile) ;

                    //逐个上传缺陷文件
                    CompactFormatterPlus cfp = new CompactFormatterPlus();
                    byte[] linkFileBuffer = cfp.Serialize(linkFile);
                    if (File.Exists(linkFile.FullFileName))
                    {

                        FileStream fs = new FileStream(linkFile.FullFileName, FileMode.Open);
                        byte[] fileBuffer = new byte[fs.Length];
                        fs.Seek(0, SeekOrigin.Begin);
                        fs.Read(fileBuffer, 0, fileBuffer.Length);
                        fs.Close();

                        //上传文件
                        bool fileUploadOk = webService.UploadFile(AppLogic.LoginUser.UserName, linkFileBuffer, fileBuffer);

                        //更新文件上传状态
                        linkFile.ReportState = fileUploadOk ? "已上报" : "未上报";
                        linkFileService.UpdateLinkFile(linkFile);
                    }
                    
                }

                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadFlawComplete", true, flaws);

            }
            catch (Exception e)
            {
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadFlawComplete", false, flaws);
            }
        }


        /// <summary>
        /// 上传计划状态
        /// </summary>
        /// <param name="plans"></param>
        public void UploadPlanState(List<Plan> plans)
        {
            try
            {
                if (plans.Count == 0)
                {
                    CallWebserviceMessage("UploadPlanStateComplete", true, plans);
                    return;
                }

                CompactFormatterPlus cfp = new CompactFormatterPlus();
                byte[] plansBuffer = cfp.Serialize(plans);

                webService.BeginUploadPlanState(AppLogic.LoginUser.UserName, plansBuffer, UploadPlanStateComplete, plans);

            }
            catch (Exception e)
            {
                CallWebserviceMessage("UploadPlanStateComplete", false, plans);
            }

        }

        /// <summary>
        /// 上传巡视计划状态完成
        /// </summary>
        /// <param name="ar"></param>
        private void UploadPlanStateComplete(IAsyncResult ar)
        {
            List<Plan> plans = (List<Plan>)ar.AsyncState;
            try
            {
                bool isSuccess = webService.EndUploadPlanState(ar);
                if (!isSuccess)
                {
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadPlanStateComplete", false, plans);
                    return;
                }

                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadPlanStateComplete", true, plans);

            }
            catch (Exception e)
            {
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadPlanStateComplete", false, plans);
            }
        }

        /// <summary>
        /// 上传GPS轨迹
        /// </summary>
        /// <param name="gpsTraces"></param>
        public void UploadGPSTrace(List<GPSTrace> gpsTraces)
        {
            try
            {
                GPSUploadDateTime gpsUploadDateTime = new GPSUploadDateTime();

                if (gpsTraces.Count == 0)
                {
                    CallWebserviceMessage("UploadGPSTraceComplete", true, gpsUploadDateTime);
                    return;
                }
                else
                {
                    gpsUploadDateTime.BeginDateTime = gpsTraces[0].CollectDateTime;
                    gpsUploadDateTime.EndDateTime = gpsTraces[gpsTraces.Count - 1].CollectDateTime;
                }

                //更新轨迹状态
                AppLogic.gpsTraceService.UpdateGPSTraceReportState(gpsUploadDateTime.BeginDateTime.Value, gpsUploadDateTime.EndDateTime.Value, "正在上报");


                CompactFormatterPlus cfp = new CompactFormatterPlus();
                byte[] gpsTracesBuffer = cfp.Serialize(gpsTraces);

                webService.BeginUploadGPSTrace(AppLogic.LoginUser.UserName, gpsTracesBuffer, UploadGPSTraceComplete, gpsUploadDateTime);


            }
            catch (Exception e)
            {
                CallWebserviceMessage("UploadGPSTraceComplete", false, null);
            }
        }

        /// <summary>
        /// 上传GPS轨迹完成
        /// </summary>
        /// <param name="ar"></param>
        private void UploadGPSTraceComplete(IAsyncResult ar)
        {
            GPSUploadDateTime gpsUploadDateTime = (GPSUploadDateTime)ar.AsyncState;
            try
            {
                bool isSuccess = webService.EndUploadGPSTrace(ar);
                if (!isSuccess)
                {
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadGPSTraceComplete", false, null);
                    return;
                }

                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadGPSTraceComplete", true, gpsUploadDateTime);

            }
            catch (Exception e)
            {
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadGPSTraceComplete", false, null);
            }
        }

        /// <summary>
        /// 上传指挥信息
        /// </summary>
        /// <param name="communications"></param>
        public void UploadCommunication(List<Communication> communications)
        {
            try
            {
                if (communications.Count == 0)
                {
                    CallWebserviceMessage("UploadCommunicationComplete", true, communications);
                    return;
                }

                //更新上传状态
                CommunicationService communicationService = new CommunicationService();
                communicationService.UpdateReportState(communications, "正在上传");

                CompactFormatterPlus cfp = new CompactFormatterPlus();
                byte[] communicationsBuffer = cfp.Serialize(communications);

                webService.BeginUploadCommunication(AppLogic.LoginUser.UserName, communicationsBuffer, UploadCommunicationComplete, communications);


            }
            catch (Exception e)
            {
                CallWebserviceMessage("UploadCommunicationComplete", false, communications);
            }
        }

        /// <summary>
        /// 指挥信息上传完成
        /// </summary>
        /// <param name="ar"></param>
        private void UploadCommunicationComplete(IAsyncResult ar)
        {
            List<Communication> communications = (List<Communication>)ar.AsyncState;
            try
            {
                bool isSuccess = webService.EndUploadCommunication(ar);
                if (!isSuccess)
                {
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadCommunicationComplete", false, communications);
                    return;
                }

                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadCommunicationComplete", true, communications);
            }
            catch (Exception e)
            {
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadCommunicationComplete", false, communications);
            }
        }

        /// <summary>
        /// 上报测温信息
        /// </summary>
        /// <param name="tempratures"></param>
        public void UploadTemprature(List<Temprature> tempratures)
        {
            try
            {
                if (tempratures.Count == 0)
                {
                    CallWebserviceMessage("UploadTempratureComplete", true, tempratures);
                    return;
                }

                //更新上传状态
                TempratureService tempratureService = new TempratureService();
                tempratureService.UpdateReportState(tempratures, "正在上传");

                CompactFormatterPlus cfp = new CompactFormatterPlus();
                byte[] tempraturesBuffer = cfp.Serialize(tempratures);

                webService.BeginUploadTemprature(AppLogic.LoginUser.UserName, tempraturesBuffer, UploadTempratureComplete, tempratures);


            }
            catch (Exception e)
            {
                CallWebserviceMessage("UploadTempratureComplete", false, tempratures);
            }
        }

        /// <summary>
        /// 上传测温信息完成
        /// </summary>
        /// <param name="ar"></param>
        private void UploadTempratureComplete(IAsyncResult ar)
        {
            List<Temprature> tempratures = (List<Temprature>)ar.AsyncState;
            try
            {
                bool isSuccess = webService.EndUploadTemprature(ar);
                if (!isSuccess)
                {
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadTempratureComplete", false, tempratures);
                    return;
                }

                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadTempratureComplete", true, tempratures);
            }
            catch (Exception e)
            {
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadTempratureComplete", false, tempratures);
            }
        }

        /// <summary>
        /// 上报巡视记录
        /// </summary>
        /// <param name="patrolLogs">巡视日志</param>
        /// <param name="patrolDetails">巡视详情</param>
        public void UploadPatrolInfo(List<PatrolLog> patrolLogs, List<PatrolDetail> patrolDetails)
        {
            List<object> patrolInfo = new List<object>();
            patrolInfo.Add(patrolLogs);
            patrolInfo.Add(patrolDetails);
            try
            {
                if (patrolLogs.Count == 0 && patrolDetails.Count ==0)
                {
                    CallWebserviceMessage("UploadPatrolInfoComplete", true, patrolInfo);
                    return;
                }

                CompactFormatterPlus cfp = new CompactFormatterPlus();
                byte[] patrolLogsBuffer = cfp.Serialize(patrolLogs);
                byte[] patrolDetailsBuffer = cfp.Serialize(patrolDetails);

                webService.BeginUploadPatrolInfo(AppLogic.LoginUser.UserName, patrolLogsBuffer,patrolDetailsBuffer, UploadPatrolInfoComplete, patrolInfo);

            }
            catch (Exception e)
            {
                CallWebserviceMessage("UploadPatrolInfoComplete", false, patrolInfo);
            }
        }

        /// <summary>
        /// 上传巡视记录完成
        /// </summary>
        /// <param name="ar"></param>
        private void UploadPatrolInfoComplete(IAsyncResult ar)
        {
            List<object> patrolInfo = (List<object>)ar.AsyncState;
            try
            {
                bool isSuccess = webService.EndUploadPatrolInfo(ar);
                if (!isSuccess)
                {
                    mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadPatrolInfoComplete", false, patrolInfo);
                    return;
                }

                //上传巡视对应的文件
                List<PatrolDetail> patrolDetails = (List<PatrolDetail>)patrolInfo[1];
                string linkIDs = "";
                foreach (PatrolDetail patrolDetail in patrolDetails)
                {
                    linkIDs += ",'" + patrolDetail.PatrolDetailID + "'";
                }
                if (linkIDs != "")
                    linkIDs = linkIDs.Remove(0, 1);
                LinkFileService linkFileService = new LinkFileService();
                List<LinkFile> linkFiles = linkFileService.GetNeedReportLinkFileByLinkID(linkIDs);
                string fileIDs = "";
                foreach (LinkFile linkFile in linkFiles)
                {
                    //更新文件上传状态
                    linkFile.ReportState = "正在上报";
                    linkFileService.UpdateLinkFile(linkFile);

                    //逐个上传缺陷文件
                    CompactFormatterPlus cfp = new CompactFormatterPlus();
                    byte[] linkFileBuffer = cfp.Serialize(linkFile);
                    byte[] fileBuffer = null ;
                    if (File.Exists(linkFile.FullFileName))
                    {

                        FileStream fs = new FileStream(linkFile.FullFileName, FileMode.Open);
                        fileBuffer = new byte[fs.Length];
                        fs.Seek(0, SeekOrigin.Begin);
                        fs.Read(fileBuffer, 0, fileBuffer.Length);
                        fs.Close();

                    }

                    //上传文件
                    bool fileUploadOk = webService.UploadFile(AppLogic.LoginUser.UserName, linkFileBuffer, fileBuffer);

                    //更新文件上传状态
                    linkFile.ReportState = fileUploadOk ? "已上报" : "未上报";
                    linkFileService.UpdateLinkFile(linkFile);
                }

                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadPatrolInfoComplete", true, patrolInfo);
            }
            catch (Exception e)
            {
                mainTreahComponent.Invoke(invokeCallWebserviceMessage, "UploadPatrolInfoComplete", false, patrolInfo);
            }
        }

        /// <summary>
        /// 同步下一个信息
        /// </summary>
        private void SynchronizeNext()
        {
            switch (synchronizePercent)
            {
                case 0 ://上传GPS轨迹
                    List<GPSTrace> gpsTraces = AppLogic.gpsTraceService.GetNeedReportGPSTrace(AppLogic.LoginUser.UserName);
                    UploadGPSTrace(gpsTraces);
                    break ;
                case 10://上传指挥信息
                    CommunicationService communicationService = new CommunicationService();
                    List<Communication> communications = communicationService.GetNeedReportCommunication(AppLogic.LoginUser.UserName);
                    UploadCommunication(communications);
                    break ;
                case 20://上传测温信息
                    TempratureService tempratureService = new TempratureService();
                    List<Temprature> tempratures = tempratureService.GetNeedReportTemprature(AppLogic.LoginUser.UserName);
                    UploadTemprature(tempratures);
                    break ;
                case 30://上传缺陷
                    FlawService flawService = new FlawService();
                    UploadFlaws(flawService.GetNeedReportFlaw(AppLogic.LoginUser.UserName));
                    break;
                case 40://上传巡视记录
                    PatrolInfoService patrolInfoSerivce = new PatrolInfoService();
                    List<PatrolLog> patrolLogs;
                    List<PatrolDetail> patrolDetails;
                    patrolInfoSerivce.GetNeedReportPatrolInfo(AppLogic.LoginUser.UserName, out patrolLogs, out patrolDetails);
                    UploadPatrolInfo(patrolLogs, patrolDetails);
                    break;
                case 50://上传任务状态
                    if (!synchronizeHasError)  //如果上传中有错误，不上传任务状态，保证没有上传的数据不会被清除(任务如果已完成，上传完后会删除数据）
                    {
                        PlanService planService = new PlanService();
                        UploadPlanState(planService.GetAllPlans(AppLogic.LoginUser.UserName));
                    }
                    else
                    {
                        synchronizePercent += 10;
                        DownloadStandardDataAndDevice(AppLogic.LoginUser.UserName);
                    }
                    break;
                case 60:
                    DownloadStandardDataAndDevice(AppLogic.LoginUser.UserName);
                    break;

                default:
                    break;
            }
        }

        /// <summary>
        /// 同步系统时间
        /// </summary>
        public void SynchronizeDatetime()
        {
            try
            {
                webService.BeginGetServerDateTime(SynchronizeDatetimeComplete, null);
            }
            catch (Exception e)
            {
            }
        }

        /// <summary>
        /// 时间同步调用完成
        /// </summary>
        /// <param name="ar"></param>
        private void SynchronizeDatetimeComplete(IAsyncResult ar)
        {
            try
            {
                DateTime serverDateTime = webService.EndGetServerDateTime(ar);

                SyncSystemTime syncSystemTime = new SyncSystemTime();
                syncSystemTime.SetLocalSystemTime(serverDateTime);
            }
            catch (Exception e)
            {
            }

        }

        /// <summary>
        /// 获取是否需要升级的信息
        /// </summary>
        public bool GetNeedUpdate(out long fileLen,out string serverVersion)
        {
            fileLen = 0;
            serverVersion = "";
            try
            {
                string clientVersion = AppLogic.config.GetParameter("Configuration/SystemInfo", "Version");
                if (clientVersion == "")
                    return false;

                return webService.QueryNeedUpdate(clientVersion, out fileLen, out serverVersion);
            }
            catch (Exception e)
            {

                return false;
            }
        }

        /// <summary>
        /// 下载升级文件
        /// </summary>
        public bool DownloadUpdateFile(int beginIndex,out byte[] buffer)
        {
            buffer = null;
            try
            {
                return webService.SynchronizeUpdateData(beginIndex,out buffer);
            }
            catch (Exception)
            {

                return false;
            }
        }
    }

    public delegate void SynchronizeProcessHandler(string info,int percent) ;
    public delegate void CallWebServiceCompleteHandler(string info, bool isSuccess, object userData);

}
